package com.jay.x.net.ssl;

import java.io.IOException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;

class SSLEchoClient extends Thread {
	SSLSocket socket;

	SSLEchoClient(SSLContext context, String host, int port) throws IOException {
		this.socket = (SSLSocket) context.getSocketFactory().createSocket(host,
				port);
	}

	{
		try {
			int count;
			byte[] buffer = new byte[8192];
			// send request
			socket.getOutputStream().write("hello".getBytes());
			// handshake before read
			socket.startHandshake();
			// read reply
			count = socket.getInputStream().read(buffer);
			System.out.println("client: (1) got "
					+ new String(buffer, 0, count) + ":" + count);
			// get a new session & do a full handshake
			socket.getSession().invalidate();
			socket.startHandshake();
			// send another request
			socket.getOutputStream().write(
					"hello again after new handshake".getBytes());
			// Do a partial handshake before reading the reply
			socket.startHandshake();
			// read reply
			count = socket.getInputStream().read(buffer);
			System.out.println("client: (2) got "
					+ new String(buffer, 0, count) + ":" + count);
		} catch (IOException exc) {
			exc.printStackTrace();
		} finally {
			try {
				socket.close();
				System.out.println("client: socket closed");
			} catch (IOException exc) {
				// ignored
			}
		}
	}
}